package com.pengcheng.swpush.task;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.pengcheng.swpush.util.Common;
import com.pengcheng.swpush.util.FileUtil;
import com.pengcheng.swpush.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PushTask {
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private Common common;
    @Autowired
    private JsonUtil jsonUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RestTemplate restTemplate;

    private String host="https://www.hkszy.cn";

    //发现有需要更新的商品，去更新海博系统，其他的都是来更新这个
    @Scheduled(fixedDelay = 10000)
    public void do_push()
    {
        String sql="";
        try {
            String river_path=System.getProperty("user.dir")+"\\river.txt";
            String str_river= fileUtil.read(river_path);
            String pptn_path=System.getProperty("user.dir")+"\\pptn.txt";
            String str_pptn= fileUtil.read(pptn_path);
            final int findex_river=common.is_int(str_river)?Integer.parseInt(str_river):0;
            final int findex_pptn=common.is_int(str_pptn)?Integer.parseInt(str_pptn):0;
            sql="select * from ST_RIVER_R";
            List<Map<String,Object>> list_river=jdbcTemplate.query(sql, new ResultSetExtractor<List<Map<String, Object>>>() {
                @Override
                public List<Map<String, Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {

                    List<Map<String, Object>> rows=new ArrayList<>();
                    int findex=0;
                    int fcount_column=rs.getMetaData().getColumnCount();
                    while(rs.next()&&findex<(findex_river+100))
                    {
                        if(findex>=findex_river)
                        {
                            Map<String,Object> row=new HashMap<>();
                            for(int i=1;i<=fcount_column;i++)
                            {
                                row.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
                            }
                            rows.add(row);
                        }
                        findex++;
                    }
                    return rows;
                }
            });
            for(int i=0;i<list_river.size();i++)
            {
                JSONObject res=upload_levellog(list_river.get(i));
                if(jsonUtil.get_int_by_path(res.toJSONString(),"$.code")==1)
                {
                    int new_findex=findex_river+i+1;
                    fileUtil.write(river_path,new_findex+"");
                }
                else {
                    i=list_river.size();
                }
            }
            sql="select * from ST_PPTN_R";
            List<Map<String,Object>> list_pptn=jdbcTemplate.query(sql, new ResultSetExtractor<List<Map<String, Object>>>() {
                @Override
                public List<Map<String, Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {

                    List<Map<String, Object>> rows=new ArrayList<>();
                    int findex=0;
                    int fcount_column=rs.getMetaData().getColumnCount();
                    while(rs.next()&&findex<(findex_pptn+100))
                    {
                        if(findex>=findex_pptn)
                        {
                            Map<String,Object> row=new HashMap<>();
                            for(int i=1;i<=fcount_column;i++)
                            {
                                row.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
                            }
                            rows.add(row);
                        }
                        findex++;
                    }
                    return rows;
                }
            });
            for(int i=0;i<list_pptn.size();i++)
            {
                JSONObject res=upload_rainlog(list_pptn.get(i));
                if(jsonUtil.get_int_by_path(res.toJSONString(),"$.code")==1)
                {
                    int new_findex=findex_pptn+i+1;
                    fileUtil.write(pptn_path,new_findex+"");
                }
                else {
                    i=list_pptn.size();
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            fileUtil.add_msg("do_push",common.format_exception(ex));
        }
    }

    private JSONObject upload_levellog(Map<String,Object> row)
    {
        String msg="";
        try {
            JSONObject row_river=JSONObject.parseObject(JSONObject.toJSONString(row));
            String stcd=jsonUtil.get_string_by_path(row_river.toJSONString(),"$.STCD");
            String tm=jsonUtil.get_string_by_path(row_river.toJSONString(),"$.TM");
            double z=jsonUtil.get_double_by_path(row_river.toJSONString(),"$.Z");
            String to_url=host+"/service/upload_levellog";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String,String> params=new LinkedMultiValueMap<>();
            params.add("sctd",stcd);
            params.add("tm",tm);
            params.add("z",z+"");
            HttpEntity<MultiValueMap<String,String>> request=new HttpEntity<>(params,headers);
            String result=restTemplate.postForObject(to_url,request,String.class);
            if(result==null)
            {
                msg="请求接口失败;data:"+JSONObject.toJSONString(params);
                fileUtil.add_msg("upload_levellog",msg);
                return jsonUtil.make_res(0,msg);
            }
            JSONObject res1=JSONObject.parseObject(result);
            if(!jsonUtil.get_string_by_path(res1.toJSONString(),"$.code").equals("0"))
            {
                msg="请求接口失败;data:"+JSONObject.toJSONString(params)+";返回数据:"+result;
                fileUtil.add_msg("upload_levellog",msg);
                return jsonUtil.make_res(0,msg);
            }
            else
            {
                return jsonUtil.make_res(1,"success");
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            msg=common.format_exception(ex);
            fileUtil.add_msg("upload_levellog",msg);
            return jsonUtil.make_res(0,msg);
        }
    }
    private JSONObject upload_rainlog(Map<String,Object> row)
    {
        String msg="";
        try {
            JSONObject row_river=JSONObject.parseObject(JSONObject.toJSONString(row));
            String stcd=jsonUtil.get_string_by_path(row_river.toJSONString(),"$.STCD");
            String tm=jsonUtil.get_string_by_path(row_river.toJSONString(),"$.TM");
            double drp=jsonUtil.get_double_by_path(row_river.toJSONString(),"$.DRP");
            double intv=jsonUtil.get_double_by_path(row_river.toJSONString(),"$.INTV");
            String to_url=host+"/service/upload_rainlog";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String,String> params=new LinkedMultiValueMap<>();
            params.add("sctd",stcd);
            params.add("tm",tm);
            params.add("drp",drp+"");
            params.add("intv",intv+"");
            HttpEntity<MultiValueMap<String,String>> request=new HttpEntity<>(params,headers);
            String result=restTemplate.postForObject(to_url,request,String.class);
            if(result==null)
            {
                msg="请求接口失败;data:"+JSONObject.toJSONString(params);
                fileUtil.add_msg("upload_rainlog",msg);
                return jsonUtil.make_res(0,msg);
            }
            JSONObject res1=JSONObject.parseObject(result);
            if(!jsonUtil.get_string_by_path(res1.toJSONString(),"$.code").equals("0"))
            {
                msg="请求接口失败;data:"+JSONObject.toJSONString(params)+";返回数据:"+result;
                fileUtil.add_msg("upload_rainlog",msg);
                return jsonUtil.make_res(0,msg);
            }
            else
            {
                return jsonUtil.make_res(1,"success");
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            msg=common.format_exception(ex);
            fileUtil.add_msg("upload_rainlog",msg);
            return jsonUtil.make_res(0,msg);
        }
    }
}
